{include file="public/layout" /}
<!--以下是在线编辑器 代码 -->
<script type="text/javascript" charset="utf-8" src="/static/Ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/static/Ueditor/ueditor.all.min.js"></script>
<script type="text/javascript" charset="utf-8" src="/static/Ueditor/lang/zh-cn/zh-cn.js"></script>
<!--以上是在线编辑器 代码  end-->
<body class="laytp-container" style="background-color: #FFF; overflow: auto;">
<style>
    ul.group-list {
        width: 96%;min-width: 1000px; margin: auto 5px;list-style: disc outside none;
    }
    .err{color:#F00; display:none;}
    ul.group-list li {
        white-space: nowrap;float: left;
        width: 150px; height: 25px;
        padding: 3px 5px;list-style-type: none;
        list-style-position: outside;border: 0px;margin: 0px;
    }
    .row .table-bordered td .btn,.row .table-bordered td img{
        vertical-align: middle;
    }
    .row .table-bordered td{
        padding: 8px;
        line-height: 1.42857143;
    }
    .table-bordered{
        width: 100%
    }
    .table-bordered tr td{
        border: 1px solid #f4f4f4;
    }
    .btn-success {
        color: #fff;background-color: #449d44;border-color: #398439 solid 1px;
    }
    .btn {
        display: inline-block;
        padding: 6px 12px;
        margin-bottom: 0;
        font-size: 14px;
        font-weight: 400;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        -ms-touch-action: manipulation;
        touch-action: manipulation;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        background-image: none;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    .col-xs-8 {
        width: 66.66666667%;
    }
    .col-xs-4 {
        width: 33.33333333%;
    }
    .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 {
        float: left;
    }
    .row .tab-pane h4{
        padding: 10px 0;
    }
    .row .tab-pane h4 input{
        vertical-align: middle;
    }
    .table-striped>tbody>tr:nth-of-type(odd) {
        background-color: #f9f9f9;
    }
    .ncap-form-default .title{
        border-bottom: 0
    }
    .ncap-form-default dl.row, .ncap-form-all dd.opt{
        /*border-color: #F0F0F0;*/
        border: none;
    }
    .ncap-form-default dl.row:hover, .ncap-form-all dd.opt:hover{
        border: none;box-shadow: inherit;
    }
    .addprine{display: inline; }
    .alisth{margin-top: 10px}
    .p_plus strong{cursor: pointer;margin-left: 4px;}
    .freight_template {
        font-size: 14px;
        display: inline-block;
        padding: 0px 10px;
    }
    .layui-form-label{
        width: 130px;
    }
</style>
<div class="layui-card" >
    <div class="layui-card-body">
        <form class="layui-form" action="">
        <div class="layui-tab layui-tab-brief">
            <div class="layui-tab-content">
                <blockquote class="layui-elem-quote">
                    {if $info && $info['status'] == 2}
                        审核拒绝：<span style="color: red;">{$info.reason}</span>
                    {/if}
                </blockquote>
                    <!--通用信息开始-->
                    <div class="layui-tab-item layui-show">
                        <input type="hidden" name="goods_id" value="{$info.goods_id|default=0}" />
                        <div class="ncap-form-default tab_div_1">
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品类型</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <select name="leixing_id" lay-filter="changeleixing">
                                        {foreach $leixing as $k=>$v}
                                            <option value="{$k}"  {if $info && ($k == $info['leixing_id'] || input('leixing_id') == $k) }selected="selected"{/if} >
                                            {$v}
                                            </option>
                                        {/foreach}
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item" {if $sid >0}style="display:none;"{/if} >
                                <label class="layui-form-label">供货商</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <select name="user_id" id="user_id"  class="small form-control">

                                        {foreach $suppliers as $k=>$v}
                                            <option value="{$k}"  {if $info && $k==$info['sid']}selected="selected"{/if} >
                                            {$v}
                                            </option>
                                        {/foreach}
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品名称</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="text" value="{$info.goods_name|default=''}" name="goods_name" class="layui-input" />
                                </div>
                            </div>

                            <div class="layui-form-item layui-form-text">
                                <label class="layui-form-label">商品简介</label>
                                <div class="layui-input-inline" style="width: 300px;">
                                    <textarea name="goods_remark" placeholder="请输入内容" class="layui-textarea">{$info.goods_remark|default=''}</textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品分类：</label>
                                <div class="layui-input-inline">
                                    <select name="cat1" id="cat1" lay-filter="cat1">
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                                <div class="layui-input-inline">
                                    <select name="cat2" id="cat2" lay-filter="cat2">
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                                <div class="layui-input-inline">
                                    <select name="cat3" id="cat3" lay-filter="cat3">
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                            </div>
                            <script src="/static/admin/js/cat_select.js?s=345"></script>
                            <script>
                                cat_select('cat1','cat2','cat3',"{$info.cat_id_1}","{$info.cat_id_2}","{$info.cat_id_3}","{:url('getCategory')}");
                            </script>

                            <div class="layui-form-item" >
                                <label class="layui-form-label">设置规格：</label>
                                <div class="layui-input-inline" style="width: 600px;">
                                    <table id="ggnamediv"  class="layui-table" style="width:600px">
                                        <thead>
                                        <tr>
                                            <th>规格分组</th>
                                            <th>规格名称</th>
                                            <th>操作</th>
                                        </tr>
                                        </thead>
                                        <?php $guigedata = $info?json_decode($info['spec_items'],true):[]; ?>
                                        {if !empty($guigedata)}
                                        {foreach $guigedata as $k=>$gg}
                                        <tr>
                                            <td><input type="text" class="layui-input" name="ggname[]" value="{$gg['title']}" style="width:120px;margin-bottom: 5px;"/></td>
                                            <td>
                                                {foreach $gg['items'] as $k2=>$ggitem}
                                                <div class="layui-input-inline" style="display: flex">
                                                    <input type="text" class="layui-input" name="ggname_ext[]" style="width:180px;margin-bottom:5px" value="{$ggitem['title']}" placeholder="请输入规格名称">
                                                    {if $k2==0}
                                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="addggname(this)" style="margin-left:5px;"><i class="fa fa-plus" style="font-size:14px!important"></i></button>
                                                    {else/}
                                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" data-id="{$gg->k}" id="{$ggitem['k']}" onclick="delggname(this,0)" style="margin-left:5px;"><i class="fa fa-remove" style="font-size:14px!important"></i></button>
                                                    {/if}
                                                </div>
                                                {/foreach}
                                            </td>
                                            {if $k==0}
                                            <td><button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="addggtype()">添加</button></td>
                                            {else/}
                                            <td><button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="$(this).parent().parent().remove()">删除</button></td>
                                            {/if}
                                        </tr>
                                        {/foreach}
                                        {else/}
                                        <tr>
                                            <td><input type="text" class="layui-input" name="ggname[]" value="规格" style="width:120px;margin-bottom: 5px;"/></td>
                                            <td>
                                                <div class="layui-input-inline" style="display: flex">
                                                    <input type="text" class="layui-input" name="ggname_ext[]" style="width:180px;margin-bottom:5px" value="默认规格" placeholder="请输入规格名称">
                                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="addggname(this)" style="margin-left:5px;">
                                                        <i class="fa fa-plus" style="font-size:14px!important"></i>
                                                    </button>
                                                </div>
                                            </td>
                                            <td><button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="addggtype()">添加</button></td>
                                        </tr>
                                        {/if}

                                    </table>
                                    <div class="layui-word-aux" style="width: 100%;">
                                        提示：先点击“添加按钮”添加规格分组，如：“颜色”，“尺码”，若只有一种规格则不需要添加规格分组；<br/>
                                        然后分别点击"＋"号添加规格名称，如：“红色”，“蓝色”；“大号”，“小号”；<br/>
                                        设置完成后点击“刷新规格项目表”按钮进行编辑各个规格的价格、库存等信息
                                    </div>
                                    <button type="button"  class="layui-btn layui-btn-sm layui-btn-primary" onclick="refreshgg()"><i class="fa fa-refresh" style="font-size:14px!important"></i>刷新规格项目表</button>
    <!--                                <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="lvpriceset()" id="lvpricebtn">会员价</button>-->

                                    <input type="hidden" name="info[lvprice]" value="{$info['id']?$info['lvprice']:'0'}"/>
                                    <table id="ggvaldiv" class="layui-table" style="margin-top:20px;">
                                    </table>
    <!--                                <div class="layui-form-mid layui-word-aux">注：开启会员价可设置不同会员等级显示不同价格；</div>-->
                                    <input type="hidden" name="specs" value=""/>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">每人限购数量</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="text" value="{$info.xgnum|default=10000}" name="xgnum" class="layui-input" onKeyUp="this.value=this.value.replace(/[^\d.]/g,'')" onpaste="this.value=this.value.replace(/[^\d.]/g,'')" />
                                </div>
                                <div class="layui-form-mid layui-text-em">会员最多购买几件</div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">起售数量</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="text" value="{$info.qsnum|default=1}" name="qsnum" class="layui-input" onKeyUp="this.value=this.value.replace(/[^\d.]/g,'')" onpaste="this.value=this.value.replace(/[^\d.]/g,'')" />
                                </div>
                                <div class="layui-form-mid layui-text-em">几件才开始卖</div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品销量</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="text" value="{$info.sales_sum|default=1}" name="sales_sum" class="layui-input" onKeyUp="this.value=this.value.replace(/[^\d.]/g,'')" onpaste="this.value=this.value.replace(/[^\d.]/g,'')" />
                                </div>
                                <div class="layui-form-mid layui-text-em">吸引顾客，订单支付时会自动增加</div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label" >商品缩略图：</label>
                                <input type="hidden" name="original_img" id="logo" class="layui-input" value="{$info.original_img}">
                                <button style="float:left;" type="button" class="layui-btn layui-btn-primary" onclick="uploader(this)" upload-input="logo" upload-preview="logoPreview">上传图片</button>
                                <div class="layui-form-mid layui-word-aux" style="margin-left:10px;">建议尺寸：200×200像素</div>
                                <div id="logoPreview" style="float:left;padding-top:10px;margin-left:160px;clear: both;">
                                    <div class="layui-imgbox" style="width:100px;"><div class="layui-imgbox-img"><img src="{$info.original_img}"/></div></div>
                                </div>
                            </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">商品视频：</label>
                            <div class="layui-input-inline" style="width:400px">
                                <input type="text" name="video" id="video" lay-verType="tips" class="layui-input" value="{$info['video']}">
                            </div>
                            <input type="hidden" name="video_duration" id="video_duration" value="{$info.video_duration}">
                            <button style="float:left;" type="button" class="layui-btn layui-btn-primary" upload-input="video" onclick="uploader(this)">上传视频</button>
                            <div class="layui-form-mid layui-word-aux" style="margin-left:10px;">填写视频链接或上传视频，视频链接必须为mp4格式的源链接，视频大小须在50MB以内</div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">商品图片：</label>
                            <input type="hidden" name="pics" value="{$info['pics']}" id="pics">
                            <button style="float:left;" type="button" class="layui-btn layui-btn-primary" onclick="uploader(this,true)" upload-input="pics" upload-preview="picList" >批量上传</button>
                            <div class="layui-form-mid layui-word-aux" style="margin-left:10px;">建议尺寸：640×640像素</div>
                            <div id="picList" class="picsList-class-padding" style="float:left;padding-top:10px;margin-left:160px;clear: both;" >

                               <?php if(!empty($info['pics'])){ $pics = explode(',',$info['pics']); foreach($pics as $pic){ ?>
                                <div class="layui-imgbox">
                                    <a class="layui-imgbox-close" href="javascript:void(0)" onclick="$(this).parent().remove();getpicsval('pics','picList')" title="删除">
                                        <i class="layui-icon layui-icon-close-fill"></i>
                                    </a>
                                    <span class="layui-imgbox-img"><img src="{$pic}"></span>
                                </div>
                                <?php }} ?>
                            </div>
                        </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">商品重量</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="text" value="{$info.weight|default=0}" name="weight" class="layui-input" onKeyUp="this.value=this.value.replace(/[^\d.]/g,'')" onpaste="this.value=this.value.replace(/[^\d.]/g,'')" />
                                </div>
                                <div class="layui-form-mid layui-text-em">务必设置商品重量, 用于计算物流费.以KG为单位</div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">是否包邮</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="radio" name="is_free_shipping" value="1" title="是" {if $info && $info['is_free_shipping']==1}checked{/if} lay-filter="changeship">
                                    <input type="radio" name="is_free_shipping" value="0" title="否" {if !$info || $info['is_free_shipping']==0}checked{/if} lay-filter="changeship">
                                </div>
                                <div class="layui-form-mid layui-text-em"></div>
                            </div>
                            <div class="layui-form-item freight_template">
                                <label class="layui-form-label">运费模板</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <select name="template_id">
                                        <option value="0">请选择运费模板</option>
                                        {foreach $freight_template as $template}
                                            <option value="{$template.template_id}"{if $info && $template['template_id']==$info['template_id']}selected="selected"{/if}>{$template.template_name}</option>
                                        {/foreach}
                                    </select>
                                </div>
                                <div class="layui-form-mid layui-text-em">
                                    {if empty($freight_template)}
                                    <span style="color: red;">没有可选的运费模板，请前去<a href="{:U('Freight/index')}" target="_blank">添加</a></span>
                                    {/if}
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">总库存</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="text" value="{$info.store_count|default=10000}" name="store_count" class="layui-input" onKeyUp="this.value=this.value.replace(/[^\d.]/g,'')" onpaste="this.value=this.value.replace(/[^\d.]/g,'')" />
                                </div>
                                <div class="layui-form-mid layui-text-em"></div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品搜索关键词</label>
                                <div class="layui-input-inline layui-input-wrap" style="width: 500px;">
                                    <input type="text" value="{$info.keywords}" name="keywords" class="layui-input" />
                                </div>
                                <div class="layui-form-mid layui-text-em">多个关键词，用空格隔开</div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品详情描述</label>
                                <div class="layui-input-inline" style="max-width: 700px;min-width: 500px">
                                    <textarea class="span12 ckeditor" id="goods_content" name="goods_content" title="">{$info.goods_content}</textarea>
                                </div>
                                <div class="layui-form-mid layui-text-em"></div>
                            </div>
                        {if $sid==0}
                        <div class="layui-form-item">
                            <label class="layui-form-label">审核状态</label>
                            <div class="layui-input-inline" style="max-width: 700px;min-width: 500px">
                                <input type="radio" name="status" value="1" title="审核通过" {if $info && $info['status']==1}checked{/if} >
                                <input type="radio" name="status" value="2" title="审核拒绝" {if $info && $info['status']==2}checked{/if} >
                            </div>
                            <div class="layui-form-mid layui-text-em"></div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">审核备注</label>
                            <div class="layui-input-inline" style="max-width: 700px;min-width: 500px">
                                <input type="text" value="{$info.reason}" name="reason" class="layui-input" />
                            </div>
                            <div class="layui-form-mid layui-text-em"></div>
                        </div>
                        {/if}
                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <div class="layui-input-block">
                                <button type="submit" class="layui-btn" lay-submit lay-filter="addgoods">立即提交</button>
                                <!--                <button type="reset" class="layui-btn layui-btn-primary">重置</button>-->
                            </div>
                        </div>
                        </div>
                    </div>
            </div>
        </div>
        </form>
    </div>
</div>
<video id="myvideo" style="display:none"></video>
<script>
    layui.use(function(){
        var form = layui.form;
        var layer = layui.layer;
        // 指定开关事件
        form.on('radio(changeship)', function(data){
            console.log(data);
            var is_free_shipping = data.value;
            if(is_free_shipping == 0){
                $('.freight_template').show();
            }else{
                $('.freight_template').hide();
            }
        });
        // 提交事件
        form.on('submit(addgoods)', function(data){
            var field = data.field; // 获取表单字段值
            // 显示填写结果，仅作演示用
            //layer.alert(JSON.stringify(field), {
            //     title: '当前填写的字段值'
            // });
            // 此处可执行 Ajax 等操作
            $.ajax({
                type: "POST",
                url: "{:url('update')}",
                data: field,
                success: function(res){
                    console.log(res);
                    if(res.status){
                        layer.msg('提交成功');
                        setTimeout(function(){
                            parent.layer.closeAll();
                            parent.tableIns.reload()
                        },1000)
                    }else{
                        layer.msg(res.msg);
                    }

                }
            });
            return false; // 阻止默认 form 跳转
        });
        form.on('select(changeleixing)', function (data) {
            var leixing_id = data.value; // 获得被选中的值
            getProductInput(leixing_id);
        });
        $(".layui-form input#video").bind("input change propertychange",function(event){
            var videourl = $('#video').val();
            if(videourl){
                $("#myvideo").prop("src", videourl);
                $("#myvideo")[0].addEventListener("loadedmetadata", function() {
                    var tol = Math.floor(this.duration); //获取总时长
                    $('#video_duration').val(tol);
                });
            }else{
                $('#video_duration').val(0);
            }
        })
    });
     var url="{:url('Ueditor/index',array('savePath'=>'goods'))}";
     var ue = UE.getEditor('goods_content',{
         serverUrl :url,
         zIndex: 999,
         initialFrameWidth: "100%", //初化宽度
         initialFrameHeight: 300, //初化高度
         focus: false, //初始化时，是否让编辑器获得焦点true或false
         maximumWords: 99999, removeFormatAttributes: 'class,style,lang,width,height,align,hspace,valign',//允许的最大字符数 'fullscreen',
         pasteplain:false, //是否默认为纯文本粘贴。false为不使用纯文本粘贴，true为使用纯文本粘贴
         autoHeightEnabled: true
     });


</script>
<!--多规格js-->
<script>
    getProductInput();
    function addggtype(){
        var gghtml = '<tr>';
        gghtml += '<td><input type="text" name="ggname[]" class="layui-input" value="" style="width:120px;margin-bottom: 5px;" placeholder="请输入规格分组"/></td>';
        gghtml += '<td><div class="layui-input-inline" style="display: flex"><input type="text" name="ggname_ext[]" class="layui-input" style="width:180px;margin-bottom:5px" value="" placeholder="请输入规格名称"> ' +
            '<button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="addggname(this)" style="margin-left:3px;">' +
            '<i class="fa fa-plus" style="font-size:14px!important"></i></button></div></td>';
        gghtml += '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="$(this).parent().parent().remove()">删除</button></td>';
        gghtml += '</tr>';
        $('#ggnamediv').append(gghtml);
    }
    function addggname(obj){
        var ggnameobj = $(obj).parent().parent().append('<div class="layui-input-inline" style="display: flex"><input class="layui-input" name="ggname_ext[]" type="text" style="width:180px;margin-bottom:5px" value="" placeholder="请输入规格名称"> ' +
            '<button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="delggname(this,1)" style="margin-left:3px;">' +
            '<i class="fa fa-remove" style="font-size:14px!important"></i></button></div>');
    }
    var oldgglist = {};
    function delggname(obj,type){
        let ksarrdel = [];
        let haskongdel = 0;
        $('#ggnamediv').find("input").each(function(){
            if($(this).val()=='') haskongdel = 1
        })
        if(haskongdel){
            $(obj).parent().remove();return;
        }
        // 获取点击规格名称的索引
        var mcid= $(obj).parent().index();
        var fzid = $(obj).parent().parent().parent().index();
        $(obj).parent().remove();
        specs = [];
        var i=0;
        // 规格分组
        $('input[name=ggname]').each(function(){
            var ggval = [];
            var j=0;
            $(this).parent().next().find('input').each(function(){
                ggval.push({ 'k':j,'title':$(this).val()});
                j++
            })
            specs.push({ 'k':i,'title':$(this).val(),'items':ggval});
            i++;
        });
        var len = specs.length;
        var newlen = 1;
        var h = new Array(len);
        var rowspans = new Array(len);
        for(var i=0;i<len;i++){
            var itemlen = specs[i].items.length;
            if(itemlen<=0) { itemlen = 1 };
            newlen*=itemlen;
            h[i] = new Array(newlen);
            for(var j=0;j<newlen;j++){
                h[i][j] = new Array();
            }
            var l = specs[i].items.length;
            rowspans[i] = 1;
            for(j=i+1;j<len;j++){
                rowspans[i]*= specs[j].items.length;
            }
        }
        for(var m=0;m<len;m++){
            var k = 0,kid = 0,n=0;
            for(var j=0;j<newlen;j++){
                var rowspan = rowspans[m];
                if( j % rowspan==0){
                    h[m][j]={ k:specs[m].items[kid].k,title: specs[m].items[kid].title,id: specs[m].items[kid].id};
                }else{
                    h[m][j]={ k:specs[m].items[kid].k,title:specs[m].items[kid].title,id: specs[m].items[kid].id};
                }
                n++;
                if(n==rowspan){
                    kid++; if(kid>specs[m].items.length-1) { kid=0; }
                    n=0;
                }
            }
        }
        for(var i=0;i<newlen;i++){
            var ks = [];
            for(var j=0;j<len;j++){
                ks.push( h[j][i].k);
            }
            ks =ks.join(',');
            ksarrdel.push(ks)
        }
        if(type){
            let oldgglistcopys = {}
            Object.keys(oldgglist).forEach(item => {
                if(item.split(',')[fzid] == mcid){
                    delete oldgglist[item]
                }
            })
            ksarrdel.forEach((item,index) => {
                oldgglistcopys[item] = Object.values(oldgglist)[index]
            })
            oldgglist = oldgglistcopys
            return;
        }
        let oldgglistcopy = {}
        Object.keys(Copyoldgglist).forEach(item => {
            if(item.split(',')[$(obj).attr('data-id')] == $(obj).attr('id')){
                delete Copyoldgglist[item]
            }
        })
        if(Object.values(Copyoldgglist).length < ksarrdel.length){
            // 编辑时添加新规格删除
            let idarr = Object.values(Copyoldgglist).map(item => item.id);
            let arr = [];
            Object.values(oldgglist).forEach((item,index) => {
                // 通过数据唯一值id筛选未删除的数据
                if(item.id != undefined){
                    if(idarr.some(i => i == item.id)){
                        arr.push(item)
                    }
                }else{
                    // 判断当前数据的值是否为选中取消的
                    if(Object.keys(oldgglist)[index].split(',')[fzid] != mcid){
                        arr.push(item)
                    }
                }
            })
            ksarrdel.forEach((item,index) => {
                oldgglistcopy[item] = arr[index];
            })
            // key值重新编译，数据按照顺序赋值
        }else{
            ksarrdel.forEach((item,index) => {
                oldgglistcopy[item] = Object.values(Copyoldgglist)[index]
            })
        }
        //
        oldgglist = oldgglistcopy
    }

    var price_arr = {};

    function getProductInput(leixing_id=0){
        console.log('getProductInput',leixing_id);
        var goods_id = 0;
        if(!leixing_id){
            leixing_id = 1;
        }

        $.ajax({
            type:'GET',
            data:{goods_id:goods_id,leixing_id:leixing_id},
            url:"{:url('Goods/ajaxGetPricearrNew')}",
            success:function(res){
                console.log(res);
                price_arr = res.data
                refreshgg();
            }
        });
    }


    var specs = [];
    var oldgglist = {:json_encode($newgglist)};
    function refreshgg(){
        console.log('刷新规格');
        var haskong = 0
        var ksarr = [];
        $('#ggnamediv').find("input").each(function(){
            if($(this).val()=='') haskong = 1
        })
        if(haskong){
            layer.msg('请填写完整');return;
        }

        var lvprice = $("input[name='info[lvprice]']").val();
        specs = [];
        var i=0;
        // 规格分组
        $('input[name="ggname[]"]').each(function(){
            console.log('i',i);
            var ggval = [];
            var j=0;
            $(this).parent().next().find('input').each(function(){
                ggval.push({ 'k':j,'title':$(this).val()});
                j++
            })
            specs.push({ 'k':i,'title':$(this).val(),'items':ggval});
            i++;
        });
        $('input[name=specs]').val(JSON.stringify(specs));
        console.log(specs)
        var len = specs.length;
        console.log('specs.length',specs.length);
        var newlen = 1;
        var h = new Array(len);
        var rowspans = new Array(len);
        var html = '<thead><tr>';
        for(var i=0;i<len;i++){
            html+="<th>" + specs[i].title + "</th>";
            var itemlen = specs[i].items.length;
            if(itemlen<=0) { itemlen = 1 };
            newlen*=itemlen;
            h[i] = new Array(newlen);
            for(var j=0;j<newlen;j++){
                h[i][j] = new Array();
            }
            var l = specs[i].items.length;
            rowspans[i] = 1;
            for(j=i+1;j<len;j++){
                rowspans[i]*= specs[j].items.length;
            }
        }
        console.log('newlen',newlen);
        //价格名称
        var price_len = price_arr.length
        for (var pi=0;pi<price_len;pi++){
            html += '<th>'+price_arr[pi].name+'</th>';
        }
        html += '</tr></thead>';

        for(var m=0;m<len;m++){
            var k = 0,kid = 0,n=0;
            for(var j=0;j<newlen;j++){
                var rowspan = rowspans[m];
                if( j % rowspan==0){
                    h[m][j]={ k:specs[m].items[kid].k,title: specs[m].items[kid].title, html: "<td rowspan='" +rowspan + "'>"+ specs[m].items[kid].title+"</td>\r\n",id: specs[m].items[kid].id};
                }else{
                    h[m][j]={ k:specs[m].items[kid].k,title:specs[m].items[kid].title, html: "",id: specs[m].items[kid].id};
                }
                n++;
                if(n==rowspan){
                    kid++; if(kid>specs[m].items.length-1) { kid=0; }
                    n=0;
                }
            }
        }

        var hh = "";
        for(var i=0;i<newlen;i++){

            hh+="<tr>";
            var ks = [];
            var titles = [];
            for(var j=0;j<len;j++){
                hh+=h[j][i].html;
                ks.push( h[j][i].k);
                titles.push( h[j][i].title);
            }
            ks2 =ks.join('_');
            ks =ks.join(',');
            titles =titles.join(',');
            ksarr.push(ks)
            console.log('ks',ks);
            if(typeof(oldgglist[ks])!='undefined'){
                var val = oldgglist[ks];
            }else{
                if(Object.values(oldgglist).length == 0){
                    oldgglist ={}
                }
                var val = { product_no:'',market_price:'',cost_price:'',sell_price:'',weight:'100',stock:'1000',givescore:'0',pic:'',lvprice_data:null};
                oldgglist[ks] = val;
            }
            //hh += '<td>';
            //hh += '	<input name="option['+ks+'][procode]" class="layui-input" type="text" style="width:100px" value="'+(val.procode==null?'':val.procode)+'"/>';
            //if(i==0){
            //	hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'procode\')"></i>';
            //}
            // hh += '</td>';
            //价格字段
            console.log('价格字段',val);
            for (var pi=0;pi<price_len;pi++){
                var field = price_arr[pi].field;
                //console.log(field,val[field]);
                hh += '<td>';
                hh += '	<input name="option['+ks+']['+field+']" oninput="priceChange(this,\''+field+'\')" class="layui-input" id="'+ks+'" type="text" style="width:100px;" value="'+(val[field]==null?'':val[field])+'"/>';
                if(i==0){
                    hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\''+field+'\')"></i>';
                }
                hh += '</td>';
            }
            // hh += '<td>';
            // hh += '	<input name="option['+ks+'][barcode]" class="layui-input" id="'+ks+'" oninput="barcodeChange(this)" type="text" style="width:100px;" value="'+(val.barcode==null?'':val.barcode)+'"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'barcode\')"></i>';
            // }
            // hh += '</td>';
            // hh += '<td>';
            // hh += '	<input name="option['+ks+'][name]" type="hidden" value="'+titles+'" class="layui-input"/><input name="option['+ks+'][market_price]" type="text" class="layui-input" id="'+ks+'" oninput="marketPriceChange(this)" style="width:70px" value="'+(val.market_price==null?'':val.market_price)+'"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'market_price\')"></i>';
            // }
            // hh += '</td>';
            // hh += '<td>';
            // hh += '	<input name="option['+ks+'][cost_price]" id="'+ks+'" oninput="costPriceChange(this)" type="text" class="layui-input" style="width:70px;" value="'+(val.cost_price==null?'':val.cost_price)+'"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'cost_price\')"></i>';
            // }
            // hh += '</td>';
            //
            // hh += '<td>';
            // hh += '	<input name="option['+ks+'][sell_price]" id="'+ks+'" oninput="getusd(this,'+i+')"  type="text" style="width:70px;" value="'+(val.sell_price==null?'':val.sell_price)+'" class="layui-input"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'sell_price\')"></i>';
            // }
            // hh += '</td>';
            //
            //
            // hh += '<td>';
            // hh += ' <input name="option['+ks+'][weight]" type="text" style="width:60px" value="'+(val.weight==null?'':val.weight)+'" class="layui-input"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'weight\')"></i>';
            // }
            // hh += '</td>';
            // hh += '<td>';
            // hh += ' <input name="option['+ks+'][stock]" type="text" style="width:60px" value="'+(val.stock==null?'':val.stock)+'" class="layui-input"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'stock\')"></i>';
            // }
            // hh += '</td>';
            //
            // hh += '<td>';
            // hh += ' <input name="option['+ks+'][givescore]" type="text" style="width:60px" value="'+(val.givescore==null?'':val.givescore)+'" class="layui-input"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'givescore\')"></i>';
            // }
            // hh += '</td>';
            //
            //
            // hh += '<td>';
            // hh += ' <input name="option['+ks+'][limit_start]" type="number" min="0" style="width:60px" value="'+(val.limit_start<=0?'0':val.limit_start)+'" class="layui-input"/>';
            // if(i==0){
            //     hh += ' <i class="fa fa-hand-o-down" style="cursor:pointer" title="批量设置" onclick="plset(\'limit_start\')"></i>';
            // }
            // hh += '</td>';

            // hh += '<td id="ggpic'+ks2+'"><input type="hidden" name="option['+ks+'][pic]" id="ggpicval'+ks2+'" value="'+(val.pic==null?'':val.pic)+'"/><div class="guigeimg"><img class="thumb_img" src="'+(val.pic?val.pic:'')+'" style="max-width:50px;"/><a class="layui-imgbox-close guigeimg_close" style="'+(val.pic=='' ||val.pic==null?'display:none':'display:block')+'"    href="javascript:void(0)" onclick="$(this).prev(\'.thumb_img\').attr(\'src\',\'\');$(this).parent().prev(\'input\').val(\'\');$(this).hide();" title="删除"><i class="layui-icon layui-icon-close-fill-opaque"></i></a></div> <button class="layui-btn layui-btn-sm layui-btn-primary" onclick="uploader(this)" upload-input="ggpicval'+ks2+'" upload-preview="ggpic'+ks2+'" type="button">上传</button></td>';
            hh += "</tr>";
        }
        let copyarr = {}
        ksarr.forEach(item => {
            Object.keys(oldgglist).forEach(items => {
                if(item == items){
                    copyarr[items] =oldgglist[items]
                }
            })
        })
        oldgglist = copyarr;
        html+=hh;
        $("#ggvaldiv").html(html);

    }
    function priceChange(obj,field=''){
        console.log('输入价格',obj,field);
        oldgglist[obj.id][field] = obj.value;
    }
    function marketPriceChange(obj){
        oldgglist[obj.id].market_price = obj.value;
    }
    function barcodeChange(obj){
        oldgglist[obj.id].barcode = obj.value;
    }
    function costPriceChange(obj){
        oldgglist[obj.id].cost_price = obj.value;
    }

    function plset(name){
        if(name =='procode'){
            var procode = $("input[name$='["+name+"]']").eq(0).val();
            if(procode == '') procode = randomString(6);
            $("input[name$='["+name+"]']").each(function(i,v){
                if(i>0) $(this).val(procode+ '-'+i);
            })
        }else{
            if(name =='barcode' || name == 'market_price' || name == "cost_price" || name == 'sell_price'){
                Object.values(oldgglist).forEach(item => {
                    if(name == 'barcode') return item.barcode = $("input[name$='["+name+"]']").eq(0).val()
                    if(name == 'market_price') return item.market_price = $("input[name$='["+name+"]']").eq(0).val()
                    if(name == 'cost_price') return item.cost_price = $("input[name$='["+name+"]']").eq(0).val()
                    if(name == 'sell_price') return item.sell_price = $("input[name$='["+name+"]']").eq(0).val()
                })
            }
            $("input[name$='["+name+"]']").val($("input[name$='["+name+"]']").eq(0).val());
        }
    }

    function randomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }



</script>
</body>
</html>